<?php


namespace app\zftpay\controller;


use app\BaseController;
use app\service\propertyService;

use app\service\zftService;
use app\zftpay\service\apiService;


use think\facade\Db;
use think\Queue;

class Callback extends BaseController
{
    public function getuser(){
        $api = new zftService();
        //获取当前用户支付宝ID
        $code = request()->get('auth_code');
        $oauthtoken = $api->oauthToken($code);

        if(property_exists($oauthtoken,'sub_msg')){
            return json(['info' => $oauthtoken->sub_msg]);
        }

        //Log::write($oauthtoken,"oauthtoken");
        session('user_id',$oauthtoken->user_id);
        $url=session("url");
        $this->redirect($url);
        die;
    }

    public function notice(){
        $path=dir(getcwd())->path.'/log/pay/zft/'.date('Ymd');
        if (! file_exists ( $path )) {
            mkdir ( "$path", 0777, true );
        }
        $address = $path."/".date('His').rand(100000,999999).'.txt';
        file_put_contents($address,file_get_contents("php://input"),FILE_APPEND);
        parse_str(file_get_contents($address),$result);//读取文本并变成数组
        $notify_con=file_get_contents($address);
        if($result['trade_status'] == 'TRADE_SUCCESS'){
            $billinfo=Db::table("zft_order")->where('trade_no',$result['trade_no'])->find();
            if(!empty($billinfo)){
                if($billinfo["order_status"]=="0"){
                    $res=Db::table("zft_order")->where("id",$billinfo["id"])->update(["order_status"=>"SUCCESS","pay_type"=>"1","pay_time"=>$result['gmt_payment']]);
                    $billinfo["order_status"]="SUCCESS";
                    $billinfo["pay_type"]="1";
                    $billinfo["alipay_notify_con"]=$notify_con;
                    $billinfo["pay_time"]=$result['gmt_payment'];
                    $id=Db::table("zft_order_success")->insertGetId($billinfo);
                    $jobQueueName  	  = "app\job\ZftSettleConfirmOrder";
                    $jobData       	  = [ 'id' =>$id ] ;
                    $res= \think\facade\Queue::push($jobQueueName,$jobData);



//                    $queueName  	  = "app\job\ZftNotifyUrl";
//                    $jobData       	  = [ 'id' =>$id ,"alipay_notify_con"=>$notify_con,"community_id"=>$billinfo["community_id"]] ;
//                    $resu= \think\facade\Queue::push($queueName,$jobData);
                }

            }
        }
    }
    public function noticetest(){
        $path=dir(getcwd())->path.'/log/pay/zft/'.date('Ymd');
        if (! file_exists ( $path )) {
            mkdir ( "$path", 0777, true );
        }
        $address = $path."/184232985807.txt";
        $notify_con=file_get_contents($address);
        var_dump($notify_con);exit;
        parse_str(file_get_contents($address),$result);//读取文本并变成数组
        if($result['trade_status'] == 'TRADE_SUCCESS'){
            $billinfo=Db::table("zft_order")->where('trade_no',$result['trade_no'])->find();
            if(!empty($billinfo)){
                if($billinfo["order_status"]=="0"){
                    $res=Db::table("zft_order")->where("id",$billinfo["id"])->update(["order_status"=>"SUCCESS","pay_type"=>"1","pay_time"=>$result['gmt_payment']]);


                }

            }
        }
    }

    public function test2(){
        $jobHandlerClassName  = 'app\admin\job\BillpaySettle';
        $jobQueueName  	  = "BillpaySettleQueue";
        $jobData       	  = [ 'id' => 123691 ] ;
        $isPushed = Queue::push( $jobHandlerClassName , $jobData , $jobQueueName );
        var_dump($isPushed);
    }

    public function test1(){
        $data["id"]=122017;
        $billpay=Db::table("billpay")->where("id",$data["id"])->find();
        if(empty($billpay)){
            return (new RedisQueueService())->push("BillPaySettleFailed",$data["id"]);
        }

        $propertyZftInfo=(new propertyService())->propertyZftByCommunityId($billpay["community_id"]);

        if(empty($propertyZftInfo)){
            return false;
            return json(['info' => '直付通配置为空']);
        }
        $amount=round($propertyZftInfo["taxrate"]*$billpay["pay_money"],2);

        $settle["community_id"]=$billpay["community_id"];
        $settle["billpay_id"]=$billpay["id"];
        $settle["order_money"]=$billpay["pay_money"];
        $settle["out_room_id"]=$billpay["out_room_id"];
        $settle["trade_no"]=$billpay["trade_no"];
        $settle["settle_money"]=$amount;
        $settle["out_room_id"]=$billpay["out_room_id"];

        Db::table("zft_settle_order")->where("billpay_id",$data["id"])->update($settle);
    }
    //返佣结算
    public function test(){
        $data["id"]=122050;
        $billpay=Db::table("billpay")->where("id",$data["id"])->where("scenes",5)->find();
        if(empty($billpay)){
            return (new RedisQueueService())->push("BillPaySettleFailed",$data["id"]);
        }

        $propertyZftInfo=(new propertyService())->propertyZftByCommunityId($billpay["community_id"]);

        if(empty($propertyZftInfo)){
            return false;
            return json(['info' => '直付通配置为空']);
        }
        $api=new apiService();
        $amount=round($propertyZftInfo["taxrate"]*$billpay["pay_money"],2);
        if($amount<=0){
            Db::table("billpay")->where("id",$data["id"])->update([
                "settle_status"=>1
            ]);
            return true;
        }
        $royalty_parameters=array(
            'royalty_type'=>'transfer',//'loginName',
            'trans_in_type'=>'loginName',//收入方账户类型
            'trans_in'=>'aliwykd@163.com',//收入方账户\
            'amount'=>$amount,//分账金额
        );
        $data= array(
            'out_trade_no'=> $billpay["out_trade_no"],
            'trade_no'=>$billpay["trade_no"],
            'royalty_parameters'=>$royalty_parameters,
        );

        $result = $api->settle(json_encode($data));
        var_dump($result);
        if($result->code==10000){
            $settle["community_id"]=$billpay["community_id"];
            $settle["trade_no"]=$billpay["trade_no"];
            $settle["billpay_id"]=$billpay["id"];
            $settle["order_money"]=$billpay["pay_money"];
            $settle["out_room_id"]=$billpay["out_room_id"];
            $settle["settle_money"]=$amount;
            $settle["out_room_id"]=$billpay["out_room_id"];
            $settle["settle_no"]=$result->settle_no;
            $settle["createTime"]=time();
            Db::table("zft_settle_order")->insert($settle);
        }
        var_dump($result);
        print("<info>Hello Job Started. job Data is: ".var_export($result,true)."</info> \n");


        return true;
    }

    public function settleQuery(){
        //分账查询
        //["settle_no"]=> string(32) "20220528002530020031610302254841"
        // ["trade_no"]=> string(28) "2022052822001461311426435109"

        // ["settle_no"]=> string(32) "20220528002530020031610301683226"
        // ["trade_no"]=> string(28) "2022052822001461311426450883" }

        //["settle_no"]=> "20220530002530020031610318204479"
        // ["trade_no"]=> string(28) "2022053022001461311428585624"
        $data["settle_no"]="20220608002530020031610373171775";
        $api=new apiService();
        $result = $api->settleQuery(json_encode($data));
        if($result->code==10000){
            $id=122050;
            Db::table("zft_settle_order")->where("billpay_id",$id)->update(["status"=>1]);
            Db::table("billpay")->where("id",$id)->update(["settle_status"=>1]);
        }
        var_dump($result);
    }
    public function zftorderQuery(){
        // ["trade_no"]=> string(28) "2022052822001461311426450883" }
        $id=122017;
        $data["external_id"]="20220608002530020031610371473296";
        $api=new apiService();
        $result = $api->zftorderQuery(json_encode($data));
        if($result->code==10000){
            Db::table("zft_settle_order")->where("billpay_id",$id)->update(["status"=>1]);
            Db::table("billpay")->where("id",$id)->update(["settle_status"=>1]);
        }
        var_dump($result);
    }
}